<style lang="less" scoped>
.bind-container {
  padding: 30px 20px;
}
.auth-card {
  overflow: hidden;
  border-radius: 5px;
  margin-bottom: 20px;
  .logo {
    padding: 40px 0 20px 0;
    background-color:#23a5a5;
    text-align: center;
    span {
      color:#ffffff;
      height: 40px;
      line-height: 40px;
    }
    img {
      width: 70px;
      height: 70px;
      margin:0 auto;
      border-radius: 5px;
    }
  }
  .instruction {
    background-color: #ffffff;
    padding: 17px;
    line-height: 24px;
    ul {
      padding-left: 6px;
      li{
        display: flex;
        align-items: center;
        &:before {
          content: "·";
          padding-right: 6px;
          font-size: 24px;
        }
      }
    }
  }
}
.auth-input {
  padding:0 15px;
  p {
    &:last-of-type {
      margin-bottom: 20px;
    }
  }
  .column {
    display: flex;
    height:36px;
    line-height: 36px;
    color: #454647;
    font-size: 16px;
    margin-bottom: 10px;
    position: relative;
    &:last-of-type {
      margin-bottom: 20px;
    }
    label {
      width:1.5rem;
    }
    input {
      height:36px;
      line-height: 36px;
      border-radius: 5px;
      border: 1px solid rgba(148,158,162,.25);
      padding:0 10px;
    }
    .acquire-code {
      position:absolute;
      right:0;
      margin: 6px 0;
      height: 24px;
      line-height: 24px;
      border-left: 1px solid rgba(148,158,162,.25);
      width:2rem;
      text-align: center;
      color:#23a5a5;
    }
  }
  .auth-submit {
    width:100%;
    height:36px;
    line-height: 36px;
    text-align: center;
    font-size: 16px;
    color:#ffffff;
    background: #23a5a5;
    border-radius: 5px
  }
}
.already-done {
  padding: 0 15px;
  font-size: 14px;
  line-height: 22px;
  color:#58666e;    
}

.noticer {
  height:.7rem;
  line-height: .7rem;
  background: rgba(255, 255, 131, 1);
  position: fixed;
  bottom:0;
  left:0;
  width:100%;
  color:#a50000;
  padding:0 .2rem;
  font-size:13px;
  box-sizing: border-box;
  text-align: center;
  .llse {
    float: right;
    font-size: 13px !important;
  }
  label {
    text-decoration: underline;
  }
}
</style>

<template>
  <div class="bind-container">
    <div class="auth-card">
      <div class="logo">
        <img src="~images/logo/big-logo.png"/>
        <span>恋链微应用</span>
      </div>
      <div class="instruction">
        <p>绑定之后可获得如下功能：</p>
        <ul>
          <li>实时接收业务订单物流安排</li>
          <li>查看业务订单执行进度</li>
          <li>查看配送节点信息</li>
        </ul>
      </div>
    </div>

    <div class="auth-input" v-if="showBinding">
      <div class="column">
        <label>恋链账号</label>
        <input class="flex1" v-model="logonUser" placeholder="" type="text" />
      </div>
      <div class="column">
        <label>验证码</label>
        <input class="flex1" v-model="inputCode" placeholder="" type="text" maxlength="4" />
        <div class="acquire-code" v-on:click="generateCode">{{funcText}}</div>
      </div>
      <input class="auth-submit" type="button" value="授权绑定" v-on:click="submitAuth"/>
    </div>

    <div class="auth-input" v-else>
      <p>您已绑定恋链账号，如需解除绑定点击下方按钮。</p>
      <p>解除绑定之后则不再接收到推送消息。</p>
      <input class="auth-submit" type="button" value="解除绑定" v-on:click="submitDischarge"/>
    </div>

    <!-- {{DingDatas}}123123 -->
    <!-- <div style="margin-top:20px; text-align:center">
      <input v-if="!showBinding" type="button" style="height:35px; background:rgb(35, 165, 165); color:#fff; width: 45%;" v-on:click="sendMessage(1, '3385')" value="发送测试数据(NC)" />
      <input v-if="!showBinding" type="button" style="height:35px; background:rgb(35, 165, 165); color:#fff; width: 45%;" v-on:click="sendMessage(2, '18627039584')" value="发送测试数据(电话)" />
    </div> -->
    <div class="noticer" v-if="showNotice">
      微信关注“<label id="copyField" v-on:click="copy">恋链</label>”公众号，可查看全部订单追溯状态！
      <i class="llse llse-del" v-on:click="showNotice = !showNotice"></i>
    </div>
  </div>
</template>

<script>
export default {
  name: "OAuth",
  data() {
    return {
      logonUser: '',
      baseCode: '',
      inputCode: '',
      funcText: '获取验证码',
      second: 60,
      disabled: true,
      clock: null,
      showBinding: true,
      userinfo: null,
      showNotice: true,
    };
  },
  computed: {
    DingDatas(){
      return localStorage.getItem('DD_Data') ? JSON.parse(localStorage.getItem('DD_Data')) : null;
    },
  },
  created() {
    this.userinfo = localStorage.getItem('userinfo') ? JSON.parse(localStorage.getItem('userinfo')) : null
    this.checkForBind();
  },
  mounted() {

  },
  methods: {
    //检查绑定信息
    checkForBind(){
      //已经绑定过且登录过的
      if(this.DingDatas && this.userinfo) {
        if(this.userinfo.DDUnionID === this.DingDatas.unionid) {
          this.showBinding = false;
        } else {
          this.showBinding = true;
        }
      //登录信息丢失的情况
      } else {
        this.GetUserInfo(1);
      }
    },

    //获取用户信息
    GetUserInfo(flag){
      let query = {
        DDUnionID: this.DingDatas.unionid,
      };
       this.Ajax.post('CheckDingDingUnionID', query).then((res) => {
        if (res.IsSuccess) {
          if(res.Data) {
            localStorage.setItem('userinfo', JSON.stringify(res.Data));
            if(flag == 1) {
              this.userinfo = res.Data;
              this.checkForBind();
            }
          } else {
            this.showBinding = true;
          }
        } else {
          this.Toast({
            message: '操作异常，请稍后重试',
          });
        };
      }).catch(e => {
          this.Toast({
            message: e || '操作异常，请稍后重试',
          });
      });
    },

    //提交绑定
    submitAuth(){
      let testTel = /^1[345789]\d{9}$/;
      if(!this.logonUser || !testTel.test(this.logonUser)){
        this.Toast('请输入您的正确手机号码！');
        return false;
      }
      if (this.inputCode != this.baseCode || !this.inputCode) {
        this.Toast('请填写正确的验证码！');
        return false;
      }
      this.AutoBind();
    },

    //绑定钉钉账号。
    AutoBind(){
      let query = {
        LogonUser: this.logonUser,
        DDOpenID: this.DingDatas.openid,
        DDUnionID: this.DingDatas.unionid,
      };
      this.Ajax.post('AutoDingDingBind', query).then((res) => {
        if (res.IsSuccess) {
          if(res.Data) {
            this.Toast({
              message: '操作已完成'
            });
            this.userinfo = res.Data;
            localStorage.setItem('userinfo', JSON.stringify(res.Data));
            this.checkForBind();
          } else {
            this.Toast({
              message: '操作异常，请稍后重试',
            });
          }
        } else {
          this.Toast({
            message: res.ErrorMessage || '操作异常，请稍后重试',
          });
        };
      }).catch(e => {
          this.Toast({
            message: e || '操作异常，请稍后重试',
          });
      });
    },

    //解除绑定
    submitDischarge(){
      this.MessageBox.confirm('解除绑定后如需消息通知等服务，则只能重新绑定；是否确定操作？').then(() => {
        let query = {
          DDOpenID: this.DingDatas.openid,
          DDUnionID: this.DingDatas.unionid,
        }
        this.Ajax.post('DischargeBind', query).then((res) => {
          if(res.IsSuccess){
            this.Toast({
              message: '操作已完成'
            });
            this.userinfo = null;
            localStorage.removeItem('userinfo');
            this.checkForBind();
          } else {
            this.Toast({
              message: res.ErrorMessage || '操作异常，请稍后重试',
            });
          }
        }).catch((e) => {
          this.Toast({
            message: e || '操作异常，请稍后重试',
          });
        })
      })
    },

    //验证码生成和发送逻辑
    generateCode(){
      let testTel = /^1[345789]\d{9}$/,
          Num = '';
      if(!this.logonUser || !testTel.test(this.logonUser)){
        this.Toast(`请输入您的正确手机号码！`);
        return false;
      } 
      if (!this.disabled) {
        return false;
      }
      this.disabled = false;
      this.funcText = this.second + '秒后重发';
      this.clock = window.setInterval(() =>{
        this.sendCode()
      }, 1000);
      for (var i = 0; i < 4; i++) {
        Num += Math.floor(Math.random() * 10);
      }
      this.baseCode = Num;
      //// 自动回填
      //this.telcode= this.code;
      let query = {
            MobileNo:this.logonUser,
            Content:`【恋链】 您的验证码是：${this.baseCode}。如非本人操作，请忽略本短信`,
          };
      this.Ajax.post('SendMessage',query).then((resp) => {
        if(!resp.IsSuccess) {
            this.Toast({
                message: resp.ErrorMessage,
            });
        } else {
          if (resp.Data.Status != '0') {
            window.clearInterval(this.clock);
            this.second = 60;
            this.funcText = '获取验证码';
            this.disabled = true;
            this.Toast({
                message: '验证码发送失败，请稍后再试！',
            });
          } else if(resp.IsSuccess && resp.Data.Status == '0'){
            this.Toast({
                message: '验证码发送成功！',
            });
          }
        }
      });
    },

    //调用发送
    sendCode: function() {
      this.second--;
      this.disabled = false;
      this.funcText = this.second + '秒后重发';
      if (this.second == 0) {
        window.clearInterval(this.clock);
        this.second = 60;
        this.funcText = '获取验证码';
        this.disabled = true;
      }
    },

    //复制文本
    copy(){
      let _that = this,
          txt = null;
      if (navigator.userAgent.match(/(iPhone|iPod|iPad);?/i)) {
        window.getSelection().removeAllRanges();
        let text = document.getElementById("copyField"),
            range = document.createRange();
        range.selectNode(text);
        window.getSelection().addRange(range);
        let successful = document.execCommand('copy');
        window.getSelection().removeAllRanges();
        if(successful) txt = text;
      } else {
        let text = document.getElementById("copyField").innerText;
        const textarea = document.createElement("textarea") ;
        textarea.style.position = 'fixed' ;
        textarea.style.top = 0 ;
        textarea.style.left = 0 ;
        textarea.style.border = 'none' ;
        textarea.style.outline = 'none' ;
        textarea.style.resize = 'none';
        textarea.style.background = 'transparent' ;
        textarea.style.color = 'transparent';
        textarea.value = text ;
        document.body.appendChild(textarea);
        textarea.select();
        try { 
          const msg = document.execCommand('copy') ? 'successful' : 'unsuccessful' ;
          if(msg) txt = text;
        } 
        catch (err) {
          this.Toast({
            message: '复制失败，不受支持的操作系统',
          });
        }
        document.body.removeChild(textarea)
      }
      if(txt) {
        this.MessageBox.confirm('公众号名称已复制，是否前往微信？<br>在微信通讯录内粘帖并搜索即可').then(() => {
          location.href = "weixin://";
        })
      }
    },

    //发送测试消息
    sendMessage(type, key){
      var random = new Date().valueOf();
      let query = {
        CarrierName: '测试承运商',
        BBillNo:`YW${random}`,
        Saler: '刘晓峰',
        DepartureAddress: '武汉市汉阳区',
        ArrivalAddress: '武汉市江汉区',
        State:'配送中',
        MainPoGuid: '20190711140343755000001936',
        BBillGuid: '20190711140343755000002969',
      };
      if(type == 1) {
        query.NCNo = key;
      }
      if(type == 2) {
        query.Receiver = key;
      }
      this.Ajax.post('SendDingTracingInfo', query).then((res) => {
        if (res.IsSuccess) {

        } else {

        };
      }).catch(e => {
          this.Toast({
            message: e || '操作异常，请稍后重试',
          });
      });
    }
  }
}
</script>